package main

import (
	"Golang/GeekWebook/webook/internal/repository"
	"Golang/GeekWebook/webook/internal/repository/dao"
	"Golang/GeekWebook/webook/internal/service"
	"Golang/GeekWebook/webook/internal/web"
	"Golang/GeekWebook/webook/internal/web/middleware"
	"github.com/gin-contrib/cors"
	"github.com/gin-contrib/sessions"
	"github.com/gin-contrib/sessions/cookie"
	"github.com/gin-gonic/gin"
	"gorm.io/driver/mysql" // MySQL 驱动
	"gorm.io/gorm"
	"strings"
	"time"
)

/*
* Author: JacksonCoder
* CreateTime: 2024/12/2
 */

func main() {
	db := initDB()
	server := initWebServer()
	u := initUser(db)
	u.RegisterRoutes(server)
	server.Run(":8080")
}

func initWebServer() *gin.Engine {
	server := gin.Default()

	server.Use(func(ctx *gin.Context) {
		println("这是第一个 middleware")
	})

	server.Use(func(ctx *gin.Context) {
		println("这是第二个 middleware")
	})

	// 中间件
	server.Use(cors.New(cors.Config{
		// CORS 跨域
		AllowOrigins: []string{"http://localhost:3000"},                   // 允许的来源
		AllowMethods: []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"}, // 允许的请求方法
		AllowHeaders: []string{"Origin", "Content-Type", "Authorization"}, // 允许的请求头
		//ExposeHeaders:    []string{"Content-Length"},                          // 允许的响应头
		AllowCredentials: true, // 是否允许发送Cookie
		AllowOriginFunc: func(origin string) bool {
			if strings.Contains(origin, "http://localhost") {
				// 你的开发环境
				return true
			}
			//return origin == "https://localhost:8081"
			return strings.Contains(origin, "yourcompany.com")
		},
		MaxAge: 12 * time.Hour, // 预检请求的缓存时间
	}))

	store := cookie.NewStore([]byte("secret"))
	server.Use(sessions.Sessions("mysession", store))

	// V2 更好
	//server.Use(middleware.NewLoginMiddlewareBuilder().
	//	IgnorePaths("/users/login").
	//	IgnorePaths("/users/signup").Build())

	// v1
	middleware.IgnorePaths = []string{"sss"}
	server.Use(middleware.CheckLogin())

	// 第二个服务不能忽略sss这条路径
	server1 := gin.Default()
	server1.Use(middleware.CheckLogin())

	return server
}

func initUser(db *gorm.DB) *web.UserHandler {
	ud := dao.NewUserDAO(db)
	repo := repository.NewUserRepository(ud)
	svc := service.NewUserService(repo)
	u := web.NewUserHandler(svc)
	return u
}

func initDB() *gorm.DB {
	db, err := gorm.Open(mysql.Open("root:123456@tcp(localhost:3307)/webook"))
	if err != nil {
		// 在初始化过程中    panic
		// panic 相当于整个  goroutine 结束
		//一旦初始化过程出错里，应用就不要启动了
		panic(err)
	}

	err = dao.InitTable(db)
	if err != nil {
		panic(err)
	}

	return db
}
